package com.spring.core.bean;

import com.spring.core.annotation.Bean;
import com.spring.core.context.AbstractApplicationContext;
import com.spring.util.StringUtil;

import java.lang.reflect.Method;

/**
 * 自定义bean
 *
 * @author Zee
 * @version 1.0
 * @date 2021/10/13
 */
public class CustomBean extends AbstractBean {


    @Override
    public void init(AbstractApplicationContext context) {
        System.out.println("初始化自定义bean: @Configuration @Bean...");
        for (String className : context.getClassNames()) {
            try {
                Class<?> clazz = Class.forName(className);
                if (hasAnnotationComponent(clazz,false)) {
                    Method[] methods = clazz.getMethods();
                    for (Method method : methods) {
                        if (!method.isAnnotationPresent(Bean.class)) {
                            continue;
                        }
                        Bean bean = method.getAnnotation(Bean.class);
                        String objBean = StringUtil.toLowerFirstCase(clazz.getSimpleName());
                        String beanName = method.getName();
                        if (!"".equals(bean.value())) {
                            beanName = bean.value();
                        }
                        //这里应该处理Bean方法中的参数(应该从context中或取实例进行注入) 这里我省略了
                        Object obj = method.invoke(context.getBean(objBean));
                        context.putBean(beanName, obj);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }
}
